<template>
    <Teleport to="#after-navigation" v-if="targetExists">
        <ForumManager />
    </Teleport>

    <div v-loading="loading">
        <h2>{{detailInfo && detailInfo.type == 1 ? $t('router_tit.modForum') : $t('router_tit.modForum2')}}</h2>
        <h3 class="discuss-name">{{ detailInfo && detailInfo.title }}</h3>
        <!-- <div class="discuss-settings-menu">
            <el-dropdown>
                <span class="el-dropdown-link">
                    <el-icon size="16"><Setting /></el-icon>
                    <span>设定</span>
                    <el-icon size="16"><CaretBottom /></el-icon>
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item>將討論標記星號</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div> -->
        <div class="nav-top">
            <div class="book-prev" v-if="detailInfo && detailInfo.prev && detailInfo.prev.id">
                <el-icon size="16" color="#4c4c4c"><CaretLeft /></el-icon>
                <router-link :to="{ name: `modForumDiscuss`, query: { id: detailInfo && detailInfo.prev.id} }">
                    <span style="color: #4c4c4c;">{{ detailInfo && detailInfo.prev.title }}</span>
                </router-link>
            </div>
            <div class="book-next" v-if="detailInfo && detailInfo.next && detailInfo.next.id">
                <router-link :to="{ name: `modForumDiscuss`, query: { id: detailInfo && detailInfo.next.id} }">
                    <span style="color: #4c4c4c;">{{ detailInfo && detailInfo.next.title }}</span>
                </router-link>
                <el-icon size="16" color="#4c4c4c"><CaretRight /></el-icon>
            </div>
        </div>
        <!-- <el-select v-model="mode" placeholder="Select" style="width: 340px" size="large">
            <el-option label="以平舖方式呈現回應的貼文，最早貼出的在前" value="1" />
            <el-option label="以平舖方式呈現回應的貼文，最晚貼出的在前" value="-1" />
            <el-option label="以樹狀結構呈現回應的貼文" value="2" />
            <el-option label="以縮排方式呈現回應的貼文" value="3" />
        </el-select> -->
        <div class="forum-post-box">
            <div class="post-header">
                <div class="user-picture pic">
                    <img :src="detailInfo && detailInfo.creator.avatar_url" v-if="detailInfo && detailInfo.creator.avatar_url" />
                    <el-icon size="20" color="#fff" v-else><User /></el-icon>
                </div>
                <div class="user-info">
                    <div class="fullname over-1">{{ detailInfo && detailInfo.title }}</div>
                    <div class="date over-1">
                        {{$t('notice-txt.detail.from-txt')}}
                        <router-link style="color: #000000" :to="`/console/user/${detailInfo && detailInfo.creator.id}?courseId=${detailInfo && detailInfo.course.id}`">{{
                            detailInfo && detailInfo.creator.name
                        }}</router-link>
                        {{$t('notice-txt.detail.to-txt')}}{{ formatDate(detailInfo && detailInfo.created_at) }}
                    </div>
                </div>
            </div>
            <div class="post-body rich-box" v-if="isEdit">
                <el-form :model="dataForm" ref="ruleFormRef" v-loading="addBtnLoading" :rules="rules" label-width="auto" label-position="left">
                    <el-form-item :label="$t('notice-txt.add-form.add-form-label1')" required prop="title">
                        <el-input v-model="dataForm.title" />
                    </el-form-item>
                    <el-form-item :label="$t('notice-txt.add-form.add-form-label2')" required prop="content">
                        <RichTextEditor v-model="dataForm.content" @update-richValue="dataForm.content = $event" />
                    </el-form-item>
                    <el-form-item label=" ">
                        <el-button color="#F06423" v-loading="addBtnLoading" @click="submitForm(ruleFormRef)">{{$t('notice-txt.add-form.edit-form-btn-submit')}}</el-button>
                        <el-button color="#435764" @click="hideEditForm()">{{$t('notice-txt.add-form.add-form-btn-cancel')}}</el-button>
                        <!-- <el-button color="#F06423" link>進階</el-button> -->
                    </el-form-item>
                </el-form>
            </div>
            <div class="post-body rich-box" v-else v-html="detailInfo && detailInfo.content"></div>

            <div class="post-actions">
                <!-- <span class="post-action">永久鏈接</span> -->
                <span class="post-action" @click="showEditForm()" v-if="roleStore.isSuperAdmin || roleStore.isTeacher">{{$t('notice-txt.detail.edit-txt')}}</span>
                <span class="post-action" @click="deleteAction()" v-if="roleStore.isSuperAdmin || roleStore.isTeacher">{{$t('notice-txt.detail.delete-txt')}}</span>
                <span class="post-action" @click="showReply(0)">{{$t('notice-txt.detail.reply-txt')}}</span>
            </div>
            <div class="reply-wrap" v-if="isShowReply">
                <el-form-item label="">
                    <el-input v-model="replyForm.content" type="textarea" :autosize="{ minRows: 4, maxRows: 10 }" :placeholder="$t('notice-txt.detail.replyForm-place')" />
                </el-form-item>
                <el-form-item label="">
                    <el-button color="#F06423" v-loading="addBtnLoading" @click="submitReply()">{{$t('notice-txt.add-form.add-form-btn-submit')}}</el-button>
                    <el-button color="#435764" @click="hideReply()">{{$t('notice-txt.add-form.add-form-btn-cancel')}}</el-button>
                </el-form-item>
            </div>
        </div>
        <div class="discussion-list">
            <reply :discussionList="discussionList" :detailInfo="detailInfo" @relRefresh="getDiscussionList" />
            

            <!-- <div class="forum-post-box" v-for="(item, index) in discussionList" :key="index">
                <div class="post-header">
                    <div class="user-picture pic">
                        <el-icon size="20" color="#fff"><User /></el-icon>
                    </div>
                    <div class="user-info">
                        <div class="fullname over-1">回應: {{ detailInfo && detailInfo.title }}</div>
                        <div class="date over-1">
                            由
                            <router-link :to="`/console/user/${item.creator.id}?courseId=${detailInfo && detailInfo.course.id}`">{{
                                item.creator.name
                            }}</router-link>
                            發表於{{ formatDate(item.created_at) }}
                        </div>
                    </div>
                </div>
                <div class="post-body rich-box" v-html="item.content"></div>

                <div class="post-actions">
                    <span class="post-action" @click="showReply(0)">回复</span>
                </div>
                <div class="reply-wrap" v-if="isShowReply">
                    <el-form-item label="">
                        <el-input v-model="replyForm.content" type="textarea" :autosize="{ minRows: 4, maxRows: 10 }" placeholder="您的回应..." />
                    </el-form-item>
                    <el-form-item label="">
                        <el-button color="#F06423" v-loading="addBtnLoading" @click="submitReply()">贴文到讨论区中</el-button>
                        <el-button color="#435764" @click="hideReply()">取消</el-button>
                    </el-form-item>
                </div>
            </div> -->
        </div>
        <div class="nav-top">
            <div class="book-prev" v-if="detailInfo && detailInfo.prev && detailInfo.prev.id">
                <el-icon size="16" color="#4c4c4c"><CaretLeft /></el-icon>
                <router-link :to="{ name: `modForumDiscuss`, query: { id: detailInfo && detailInfo.prev.id} }">
                    <span style="color: #4c4c4c;">{{ detailInfo && detailInfo.prev.title }}</span>
                </router-link>
            </div>
            <div class="book-next" v-if="detailInfo && detailInfo.next && detailInfo.next.id">
                <router-link :to="{ name: `modForumDiscuss`, query: { id: detailInfo && detailInfo.next.id} }">
                    <span style="color: #4c4c4c;">{{ detailInfo && detailInfo.next.title }}</span>
                </router-link>
                <el-icon size="16" color="#4c4c4c"><CaretRight /></el-icon>
            </div>
        </div>
    </div>
    
</template>

<script setup lang="ts">
import reply from './reply.vue';
import { computed, onMounted, ref, reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
import moment from 'moment'
// moment.locale('en');
import ForumManager from '@/components/ForumManager.vue'
import CourseService from '@/api/course'
const route = useRoute()
const id = computed(() => Number(route.query.id))
const mode = ref('1')
const targetExists = ref(false)
import RichTextEditor from '@/components/RichTextEditor.vue'
import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
const { locale, t } = useI18n<{ message: MessageSchema }, SupportedLocales>()
// 获取详情
const loading = ref(false)
const detailInfo = ref()
const getDetailsAction = () => {
    loading.value = true
    CourseService.getCourseNoticeDetail(id.value)
        .then(res => {
            detailInfo.value = res
        })
        .finally(() => {
            loading.value = false
        })
}

// 编辑
import { useRoleStore } from '@/stores/role'
const roleStore = useRoleStore()
import type { FormInstance, FormRules } from 'element-plus'
const isEdit = ref(false)
const showEditForm = () => {
    dataForm.title = detailInfo.value.title
    dataForm.content = detailInfo.value.content
    isEdit.value = true
}
const hideEditForm = () => {
    dataForm.title = ''
    dataForm.content = ''
    isEdit.value = false
}
const ruleFormRef = ref<FormInstance>()
const dataForm = reactive({
    title: '',
    content: '',
})
const rules = reactive({
    title: [
        {
            required: true,
            message: t("notice-txt.add-form.add-form-rules1"),
            trigger: 'blur',
        },
    ],
    content: [
        {
            required: true,
            message: t("notice-txt.add-form.add-form-rules2"),
            trigger: 'blur',
        },
    ],
})
// 新增课程公告

const submitForm = async (formEl: { validate: (arg0: (valid: any, fields: any) => void) => any }) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            EditCourseNoticeAction()
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 提交
const addBtnLoading = ref(false)
const EditCourseNoticeAction = () => {
    addBtnLoading.value = true
    const params = {
        title: dataForm.title,
        content: dataForm.content,
        status: 1,
    }
    CourseService.putCourseNotice(id.value, params)
        .then(res => {
            getDetailsAction()
        })
        .finally(() => {
            addBtnLoading.value = false
        })
}

// 删除当前公告
const deleteAction = () => {
    ElMessageBox.confirm(t('notice-txt.detail.delete_tips'), t('notice-txt.detail.delete_header_tips'), {
        confirmButtonText: t('golbal.btn_text_4'),
        cancelButtonText: t('golbal.btn_text_3'),
        type: 'warning',
    })
        .then(() => {
            CourseService.deleteCourseNotice(id.value)
                .then(res => {
                    router.go(-1)
                })
                .finally(() => {})
        })
        .catch(() => {})
}
// 获取评论区列表
const discussionList = ref([])
const discussionLoading = ref(false)
const getDiscussionList = () => {
    discussionLoading.value = true;
    CourseService.getCourseDiscussion(id.value)
        .then(res => {
            let list = res.discussions;
            list.map(item => {
                item.replyForm = {
                    content: '',
                    parent_id: 0,
                }
                item.isShowReply = false;
                item.submitLoading = false;
            })
            discussionList.value = list;
        })
        .finally(() => {
            discussionLoading.value = false;
        })
}
// 回复Form
const replyForm = reactive({
    content: '',
    parent_id: 0,
})
const isShowReply = ref(false)
const showReply = (parentId: number) => {
    replyForm.content = '';
    replyForm.parent_id = parentId;
    isShowReply.value = true;
}
const hideReply = () => {
    replyForm.content = '';
    isShowReply.value = false;
}
// 提交回复
const submitReply = () => {
    const params = {
        course_id: detailInfo.value.course_id,
        notice_id: id.value,
        content: replyForm.content,
        parent_id: replyForm.parent_id,
    };
    CourseService.postCourseDiscussion(params)
        .then(res => {
            replyForm.content = ''
            replyForm.parent_id = 0
            getDiscussionList()
        })
        .finally(() => {
            discussionLoading.value = false;
        })
}


// 处理方法：中文日期 + 英文星期 + 时间
const formatDate = (dateString: any) => {
    // 保存当前语言设置
    const originalLocale = moment.locale()
    // 1. 先获取英文星期缩写（ddd）
    moment.locale('en') // 临时切换为英文
    const weekday = moment.unix(dateString).format('ddd')
    // 2. 切换回中文环境，获取年月日和时间
    moment.locale('zh-cn') // 切换为中文
    const dateTime = moment.unix(dateString).format('YYYY年 MM月 DD日')
    const time = moment.unix(dateString).format('HH:mm')
    // 3. 恢复原始语言设置
    moment.locale(originalLocale)
    // 组合结果
    return `${dateTime}(${weekday}) ${time}`
}
onMounted(() => {
    targetExists.value = !!document.querySelector('#after-navigation')
    
})
// 监听路由参数变化
watch(
  () => route.query, 
  (newParams, oldParams) => {
    getDetailsAction()
    getDiscussionList()
    // 执行参数变化后的逻辑（如重新加载数据）
  },
  { immediate: true } // 初始加载时立即执行一次
)
</script>

<style lang="less" scoped>
.reply-wrap{
    padding: 15px;
    background-color: #FAFAFA;
}
h2 {
    margin-bottom: 30px;
    font-size: 30px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

h3 {
    margin-bottom: 18px;
    font-size: 26px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

.discuss-settings-menu {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;

    .el-dropdown-link {
        display: flex;
        align-items: center;
        gap: 4px;
    }
}

.nav-top {
    padding: 15px 0;

    // display: flex;
    // align-items: center;
    // justify-content: space-between;
    height: auto;
    width: 100%;
    overflow: hidden;
    .book-prev{
        float: left;
    }
    .book-next{
        float: right;
    }
    .book-prev,
    .book-next {
        color: #4c4c4c;
        font-size: 15px;
        cursor: pointer;
        display: flex;
        align-items: center;

        &:hover {
            color: #f06423;
            span{
                color: #f06423 !important;
            }
            .el-icon {
                color: #f06423;
            }
        }
    }
}

.forum-post-box {
    margin-top: 8px;
    border-radius: 3px;
    border: 1px solid #0000001a;

    .post-header {
        padding: 8px 15px;
        background-color: #f9f9f9;

        display: flex;
        align-items: center;
        gap: 8px;

        .user-picture {
            border-radius: 50%;
            width: 45px;
            height: 45px;
            background-color: #e6e5e5;

            display: flex;
            align-items: center;
            justify-content: center;
        }

        .user-info {
            flex-grow: 1;

            .fullname,
            .date {
                font-size: 12px;
                color: #212529;
                line-height: 1.25;
            }

            .fullname {
                margin-bottom: 4px;
                font-weight: bold;
            }
        }
    }

    .post-body {
        padding: 15px;
    }

    .post-actions {
        border-top: 1px solid #0000001a;
        padding: 15px;

        display: flex;
        align-items: center;
        justify-content: flex-end;
        gap: 15px;

        .post-action {
            line-height: 1.6;
            color: #a5a5a5;
            font-size: 12px;
            cursor: pointer;

            &:hover {
                color: #f06423;
            }
        }
    }
}
</style>
